package org.springframework.beans.support;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import java.io.Serializable;
import java.util.*;

/**
 * DefaultListableBeanFactory
 *
 * @author xiaohei
 */
public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements BeanDefinitionRegistry,
        ConfigurableListableBeanFactory, Serializable {

    private Map<String, BeanDefinition> beanDefinitionMap = new HashMap<>();

    private Set<String> manualSingletonNames = new HashSet<>();


    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition) {
        BeanDefinition oldBeanDefinition = beanDefinitionMap.get(beanName);
        if (oldBeanDefinition != null) {
            throw new BeansException("beanDefinition of " + beanName + " is exist");
        }
        beanDefinitionMap.put(beanName, beanDefinition);
    }

    @Override
    public BeanDefinition getBeanDefinition(String beanName) throws BeansException {
        BeanDefinition beanDefinition = beanDefinitionMap.get(beanName);
        if (beanDefinition == null) {
            throw new BeansException("not bean named " + beanName + " is defined");
        }
        return beanDefinition;
    }

    @Override
    public void preInstantiateSingletons() throws BeansException {
        for (String name : beanDefinitionMap.keySet()) {
            getBean(name);
        }
    }

    @Override
    public String[] getBeanDefinitionNames() {
        return beanDefinitionMap.keySet().toArray(new String[0]);
    }

    @Override
    public <T> T getBean(Class<T> requiredType) throws BeansException {
        List<String> beanNames = getBeanNameForType(requiredType);
        if (beanNames.size() > 1) {
            throw new BeansException(requiredType + " bean not unique");
        }
        if (beanNames.isEmpty()) {
            throw new BeansException(requiredType.getName() + " beanDefinition does not exist");
        }
        return (T) getBean(beanNames.get(0));
    }

    @Override
    public void registerSingleton(String beanName, Object singletonObject) {
        super.registerSingleton(beanName, singletonObject);
        updateManualSingletonNames(beanName);
    }

    private void updateManualSingletonNames(String beanName) {
        synchronized (beanDefinitionMap) {
            if (!beanDefinitionMap.containsKey(beanName)) {
                manualSingletonNames.add(beanName);
            }
        }
    }

    @Override
    public <T> List<T> getBeanOfType(Class<T> requiredType) throws BeansException {

        List<String> beanNames = getBeanNameForType(requiredType);
        List<T> beans = new ArrayList<>();
        for (String beanName : beanNames) {
            beans.add((T) getBean(beanName));
        }
        return beans;
    }

    private List<String> getBeanNameForType(Class<?> requiredType) {
        List<String> beanNames = new ArrayList<>();
        beanDefinitionMap.forEach((beanName, beanDefinition) -> {
            if (requiredType.isAssignableFrom(beanDefinition.getBeanClass())) {
                beanNames.add(beanName);
            }
        });

        for (String beanName : manualSingletonNames) {
            Object beanInstance = getSingleton(beanName);
            if (requiredType.isAssignableFrom(beanInstance.getClass())) {
                beanNames.add(beanName);
            }
        }
        return beanNames;
    }
}
